<template>
  <div class="login-container">
    <div class="login-bg" id="login-bg">
      <!-- 可根据需要添加背景图片 -->
    </div>
    <div class="login-form">
      <div class="lf-content">
        <h3 class="lf-title">管理中心</h3>
        <div class="lf-form" @keyup.enter="submitLogin">
          <el-form :model="loginForm" :rules="loginRules" ref="loginForm" size="large">
            <el-form-item prop="username">
              <input class="input-user" v-model="loginForm.username" clearable>
              <span class="placeholder-user">账号</span>
            </el-form-item>
            <el-form-item prop="password">
              <input class="input-pwd" v-model="loginForm.password" type="password" autocompete="off" clearable
                :maxlength="20">
              <span class="placeholder-pwd">密码</span>
            </el-form-item>
            <el-form-item prop="validcode" v-if="validateInFO.validator_type === 'ALIYUN'">
              <div id="pc-valid" class="nc-container"></div>
            </el-form-item>
            <el-form-item prop="validcode" class="img-code" v-else-if="validateInFO.validator_type === 'IMAGE'">
              <div class="checkcode">
                <el-input class="input-checkcode" v-model="loginForm.validcode" :placeholder="translateKey('validcode')"
                  :maxlength="4" clearable>
                </el-input>
                <img class="checkcode-img" :src="validcodeImg" @click="changeValidcode">
              </div>
            </el-form-item>
            <div v-else></div>
            <el-form-item>
              <el-button type="primary" :loading="loading" :disabled="!accountAfsSuccess" @click="submitLogin"
                class="login-btn">
                <div class="btn-text">{{ translateKey('logIn') }}</div>
                <div class="btn-block"></div>
              </el-button>
            </el-form-item>
            <!-- <lang-select class="set-language" /> -->
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as API_common from '@/api/common'
import 'particles.js'
import particlesjsConfig from '@/assets/particlesjs-config.json'
import LangSelect from '@/components/LangSelect'
import Storage from '@/utils/storage'
import uuidv1 from 'uuid/v1'
import AliyunAfs from '@/components/AliyunAfs'

export default {
  components: { LangSelect },
  name: 'login',
  data() {
    return {
      loading: false,
      loginForm: {
        username: '',
        password: '',
        scene: 'LOGIN',
        validcode: ''
      },
      loginRules: {
        username: [
          { required: true, message: this.translateKey('val_username'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.translateKey('val_password'), trigger: 'blur' }
        ],
        validcode: [
          { required: true, message: this.translateKey('val_validcode'), trigger: 'blur' }
        ]
      },
      validcodeImg: '',
      uuid: Storage.getItem('admin_uuid'),
      // 验证信息
      validateInFO: {},
      // 阿里云验证条实例
      afs: null,
      // 当滑动验证成功之后返回的参数
      afsParam: {
        c_sessionid: '',
        sig: '',
        nc_token: ''
      },
      // 阿里云滑动验证是否通过 && 如果不是 阿里云验证则直接设置为 true
      accountAfsSuccess: false
    }
  },
  mounted() {
    const uuid = Storage.getItem('admin_uuid')
    if (uuid) {
      this.uuid = uuid
    } else {
      const _uuid = uuidv1()
      this.uuid = _uuid
      Storage.setItem('admin_uuid', _uuid, { expires: 30 })
    }
    this.changeValidcode()
    // this.loadParticles()
    /** 获取登录验证方式 **/
    API_common.getValidator().then(res => {
      this.validateInFO = res
      const { validator_type, aliyun_afs } = res
      if (validator_type === 'ALIYUN') {
        this.afs = new AliyunAfs('#pc-valid', aliyun_afs.scene, aliyun_afs.app_key, this.initCaptcha)
        this.afs.init()
      } else {
        this.accountAfsSuccess = true
      }
    })
  },
  computed: {
    siteInfo() {
      return this.$store.getters.siteInfo
    }
  },
  methods: {
    /** 阿里云滑动验证 通过后的回调函数 **/
    initCaptcha(data) {
      this.afsParam.c_sessionid = data.csessionid
      this.afsParam.sig = data.sig
      this.afsParam.nc_token = data.nc_token
      this.accountAfsSuccess = true
    },
    /** 翻译 */
    translateKey(key) {
      return this.$t('login.' + key)
    },
    /** 更换图片验证码 */
    changeValidcode() {
      this.validcodeImg = API_common.getValidateCodeUrl('LOGIN', this.uuid)
    },
    /** 表单提交 */
    submitLogin() {
      if (!this.accountAfsSuccess) return
      if (this.afs) {
        const params = this.MixinClone(this.loginForm)
        params.c_sessionid = this.afsParam.c_sessionid
        params.sig = this.afsParam.sig
        params.nc_token = this.afsParam.nc_token
        delete params.validcode
        delete params.scene
        this.loading = true
        this.$store.dispatch('loginAction', params).then(() => {
          this.loading = false
          const forward = this.$route.query.forward
          let query = JSON.parse(JSON.stringify(this.$route.query))
          delete query.forward
          this.$router.push({ path: forward || '/', query })
        }).catch(() => {
          this.loading = false
          this.afs.reload()
          this.accountAfsSuccess = false
        })
      } else {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            const params = this.MixinClone(this.loginForm)
            params.uuid = this.uuid
            params.captcha = params.validcode
            delete params.validcode
            this.loading = true
            this.$store.dispatch('loginAction', params).then(() => {
              this.loading = false
              const forward = this.$route.query.forward
              let query = JSON.parse(JSON.stringify(this.$route.query))
              delete query.forward
              this.$router.push({ path: forward || '/', query })
            }).catch(() => {
              this.loading = false
              this.changeValidcode()
            })
          } else {
            this.$message.error(this.translateKey('val_form'))
            return false
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../styles/colors.scss'; // 引入colors.scss

/deep/ .nc-container .nc_scale span {
  height: 34px;
}

.login-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;
  position: relative;
}

.login-form {
  position: absolute;
  width: 620px;
  left: 29%;
  top: 53%;
  padding: 0;
  margin-top: -240px;
  margin-left: -230px;
  z-index: 100001;

  .lf-content {
    filter: progid:DXImageTransform.Microsoft.gradient(enabled='true', startColorstr='#E5FFFFFF', endColorstr='#E5FFFFFF');
  }

  .lf-title {
    display: block;
    text-align: center;
    font-size: 40px;
    font-weight: 500;
    letter-spacing: 8px;
    background: $primary-gradient;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    text-fill-color: transparent;
  }

  .lf-title-sb {
    display: block;
    height: 30px;
    text-align: center;
    font-size: 13px;
    font-weight: normal;
    line-height: 30px;
    color: #999;
  }

  .lf-form {
    display: block;
    padding: 0 140px 30px;
    overflow: hidden;
    position: relative;

    /deep/ .el-input__inner {
      display: block;
      margin: 0;
      padding: 0;
      line-height: 45px;
      height: 45px;
      font-size: 12px;
      padding-left: 12px;
      border: 0;
    }

    .input-user {
      display: block;
      margin: 0;
      padding: 0;
      margin-top: 20px;
      padding-left: 45px;
      line-height: 45px;
      height: 45px;
      width: calc(100%);
      border: 1px solid #333;
      border-radius: 6px;
      box-sizing: border-box;
      background-color: rgba(0, 0, 0, 0);

      &:focus {
        border: 2px $primary-color;
      }

      &:focus+.placeholder-user {
        top: 13px
      }
    }

    .placeholder-user {
      position: absolute;
      display: block;
      background-color: #fff;
      padding: 0;
      margin: 0;
      font-size: 12px;
      height: 12px;
      line-height: 12px;
      color: #333;
      top: 35px;
      left: 14px;
      transition: all 1s;
    }

    .input-pwd {
      display: block;
      margin: 0;
      padding: 0;
      margin-top: 20px;
      padding-left: 45px;
      line-height: 45px;
      height: 45px;
      width: calc(100%);
      border: 1px solid #333;
      border-radius: 6px;
      box-sizing: border-box;
      background-color: rgba(0, 0, 0, 0);

      &:focus {
        border: 2px $primary-color;
      }

      &:focus+.placeholder-pwd {
        top: 13px
      }
    }

    .placeholder-pwd {
      position: absolute;
      display: block;
      background-color: #fff;
      padding: 0;
      margin: 0;
      font-size: 12px;
      height: 12px;
      line-height: 12px;
      color: #333;
      top: 35px;
      left: 14px;
      transition: all 1s;
    }

    .img-code {
      margin: 0;
      padding: 0;
      height: 65px;

      &:focus-within {
        border: 2px $primary-color;
      }

      .checkcode {
        margin-top: 20px;
        padding: 0;
        display: flex;
        border: 1px solid #000;
        box-sizing: border-box;
        border-radius: 6px;
        overflow: hidden;
      }

      .input-checkcode {
        width: 75%;
        border-radius: 0;
      }

      .checkcode-img {
        margin: 0;
        height: 45px;
        display: block;
        cursor: pointer;
        border-radius: 0;
        background: #CBECFF;
      }
    }

    .login-btn {
      padding: 0;
      margin: 40px 0 0 0;
      display: block;
      width: 100%;
      height: 100%;
      border: 1px solid #000;
      box-sizing: border-box;
      border-radius: 6px;
      overflow: hidden;
      position: relative;

      .btn-text {
        width: 100%;
        height: 100%;
        line-height: 43px;
        position: relative;
        z-index: 1;
        transition: color 0.5s;
      }

      .btn-block {
        width: 100%;
        height: 100%;
        background-color: $primary-color;
        position: absolute;
        top: 100%;
        left: 0;
        transition: transform 1s;
      }

      &:hover {
        .btn-text {
          color: #fff;
        }

        .btn-block {
          transform: translateY(-100%);
        }
      }
    }
  }
}
</style>
